<?php
namespace app\api\controller;
use think\Controller;
use app\api\model\Member as MemberModel;
use app\api\service\SmsApi as SmsApiService;
use think\Cache;
use think\Validate;

class Login extends Common
{
    /**
     * 账号密码登录
     */
    public function loginByPwd()
    {
        //判断提交方式
        if (request()->isPost()) {
            // 实例化对象
            $member = new MemberModel();
            // 接收参数
            $phone_num = input('param.phone_num');
            $password = input('param.password');
            // 返回数据
            $result = $member->loginByPwd($phone_num,$password);
            return $result;
        }
    }

    /**
     * 发送短信
     */
    public function sendMsg()
    {
        $sms = new SmsApiService();
        $phone_num = input('param.phone_num');
        $result = $sms->sendMsg($phone_num);
        return $result;
    }

    /**
     * 短信验证码登录
     */
    public function loginByMsg()
    {
        //判断提交方式
        if (request()->isPost()) {
            // 实例化对象
            $member = new MemberModel();
            // 接收参数
            $phone_num = input('param.phone_num');
            $msg_code = input('param.msg_code');
            // 返回数据
            $result = $member->loginByMsg($phone_num,$msg_code);
            return $result;
        }
    }

    /**
     * 注册账号
     */
    public function register()
    {
        //判断提交方式
        if (request()->isPost()) {
            //实例化模型
            $member = new MemberModel();
            //验证数据
            $validate = new Validate([
                ['phone_num','require|number|length:11|unique:member','手机号必填|手机号格式错误|手机号长度错误|手机号已存在'],
                ['nickname','require|length:2,8','昵称必填|昵称长度2~8位之间'],
                ['password','require|alphaNum|length:6~12','密码必填|密码只能为数字和字母|密码长度6~12位之间'],
                ['sex','require|number|length:1','性别必填|性别只能为数字|性别长度1位'],
            ]);
            $data = input('post.');
            if ($data['msg_code'] != Cache::get('phone:'.$data['phone_num'])) {
                //说明短信验证码错误
                return json(['data'=>'','code'=>1,'message'=>'验证码错误']);
            }
            if (!$validate->check($data)) {
                $message = $validate->getError();
                return json(['data'=>'','code'=>1,'message'=>$message]);
            }
            $result = $member->add($data);
            if ($result) {
                return json(['data'=>'','code'=>0,'message'=>'注册成功']);
            } else {
                return json(['data'=>'','code'=>1,'message'=>'注册失败']);
            }
        }
    }
}
